from uuid import uuid4
import os

from django.conf import settings
from .models import MFileModel
from apps.missions.models import Mission
from rest_framework import serializers
from util.exception import ValidationError


class FileListCheckSerializer(serializers.Serializer):
    filename = serializers.CharField(max_length=200, allow_null=True, allow_blank=True)
    filetype = serializers.IntegerField(allow_null=True)

    class Meta:
        model = MFileModel
        fields = ["filename", "filetype"]


class FileListSerializer(serializers.ModelSerializer):
    class Meta:
        model = MFileModel
        fields = ["filename", "filetype", "create_date", "filepath", "id", "is_exist"]


class mfileSerializer(serializers.ModelSerializer):
    filename = serializers.CharField(max_length=300, allow_null=False)
    filetype = serializers.IntegerField(allow_null=False)

    def validate_filename(self, obj):
        mfile = MFileModel.objects.filter(filename=obj).first()
        if mfile:
            raise ValidationError(12001)
        return obj

    class Meta:
        model = MFileModel
        fields = ["filename", "filetype"]

    def create(self, data):
        id = str(uuid4()).replace("-", "")
        data["id"] = id
        data["filepath"] = self.__get_file_path(data["filename"], data["filetype"])
        MFileModel.objects.create(**data)
        return id

    def __get_file_path(self, filename, filetype):
        file_path = ""
        if filetype == 1:
            file_path = "{}/{}".format(settings.UPDATE_GATEWAY_FILE_PATH, filename)
        elif filetype == 2:
            file_path = "{}/{}".format(settings.UPDATE_SENSOR_FILE_PATH, filename)
        elif filetype == 3:
            file_path = "{}/{}".format(settings.AGREEMENT_FILE_PATH, filename)
        elif filetype == 4:
            file_path = "{}/{}".format(settings.CONFIG_FILE_PATH, filename)
        return file_path


class MfileUpdateSerializer(serializers.ModelSerializer):
    key = serializers.CharField(max_length=32, allow_null=False)

    class Meta:
        model = MFileModel
        fields = ["key"]

    def validate_key(self, obj):
        mfile = MFileModel.objects.filter(id=obj).first()
        filepath = mfile.filepath
        if not mfile:
            raise ValidationError(12002)
        misssion = Mission.objects.filter(file_path=filepath, state=0).first()
        if misssion:
            raise ValidationError(12003)
        return obj

    def update(self, data):
        key = data["key"]
        mfile = MFileModel.objects.filter(id=key).first()
        filepath = mfile.filepath
        if os.path.exists(filepath):
            os.remove(filepath)
        MFileModel.objects.filter(id=key).delete()

